<{if $is_empty}>
<{include file="wap/cart/cart_empty.html" app=b2c}>
<{else}>
<!-- 购物车主体 -->
<div id="cart_main">
    <{include file="wap/cart/cart_main.html" app=b2c}>
</div>

<{/if}>
<div id='divCartHide' style="display:none;"></div>
<script type="text/javascript">
  $(function() {
	// 初始化
	$('.top_text_right').click(function(){
		  var edit = $(this).attr('edit');
		  if(edit == 1){
			  $(".edit_btn1").css('display','none');
			  $(".bottom_count_text").css('display','block');
			  $(".bottom_count_button").css('display','block');
			  $(".edit_input").css('display','none');
			  $(this).attr('edit',0);
			  $(".top_text_right").text("编辑");
			  //销毁
			  alignmentFns.destroy();

		  }else{
			  $(".edit_btn1").css('display','block');
			  $(".edit_input").css('display','block');
              $(".bottom_count_text").css('display','none');
              $(".bottom_count_button").css('display','none');
			  $(".top_text_right").text("完成");
			  $(this).attr('edit',1);
			  //初始化
			  alignmentFns.initialize();
		  }
	});
	// 设置商品数量
	function setQuantity(el,flag){
		var ipt = el.parent().find('.isYang'),
			max = parseInt(el.parents('.pt-h-item').find('.max-num').val()),
			min = parseInt(el.parents('.pt-h-item').find('.min-num').val()),
			val = ipt.val();
		switch(flag){
			case 1:
				if(!/^\d+$/.test(val))
                    ipt.val(min);
                else if(val > min)
                    ipt.val( val-1 );
                else if(val == min)
                    popup('此商品最少购买' + min + '件');
                break;
			case 2:
				if(val < max)
                    ipt.val( +val+1 );
                else if(val == max)
                    popup('此商品最多只能购买' + max + '件');
				break;
			case 3:
				if(val > max){
					popup('此商品最多只能购买' + max + '件');
					ipt.val(max);
				} else if(val < min){
					popup('此商品最少购买' + min + '件');
					ipt.val(min);
				}
				break;
		}
		function popup(msg) {
			var tpl = $('<div class="popup2">' + msg + '</div>').appendTo(document.body);
			var timer = setTimeout(function(){
				tpl.remove();
			}, 3000);
		}
		var data = $('<form action=""></form>').append(el.parents('.pt-h-item').clone()).serialize();
		$.post('<{link app=b2c ctl=wap_cart act=update}>',data+"&response_type=true",function(re){
			var o = JSON.parse(re),
				promotion = $('#order_promotion .content'),
				unuse_rule = $('#unused_promotion .content'),
				ul = '';
			if(o.promotion){
				if(o.promotion.order){
					$.each(o.promotion.order,function(){
						ul += '<li><b class="f-red">['+this.desc_tag+']</b>'+this.name+'</li>';
					});
					promotion.html(ul);
					ul = '';
				}else{
					promotion.html('');
				}
			}else{
				promotion.html('');
			}
			if(o.unuse_rule){
				$.each(o.unuse_rule,function(){
					ul += '<li><b class="f-red">['+this.desc_tag+']</b>'+this.name+'</li>';
				unuse_rule.html(ul);
				});
			}else{
				unuse_rule.html('');
			}
			el.parents('.pt-h-item').find('d').html(o.edit_ajax_data.buy_price);
			$('.bottom_count_prix').find('span').html(o.sub_total.promotion_subtotal);
			$('.J_settlement').find('span').html(o.number.cart_number);
			$('.top_cart').find('span').html(o.number.cart_number);
		});

	}
	$(".edit_input").delegate(".J-pt-num","tap",function(e){
		var el = $(e.srcElement),
			n = 0;
		if( !el.hasClass('btn1') )return;
		if( el.hasClass('minus') )n=1;
		if( el.hasClass('plus') )n=2;
		setQuantity(el,n);
	});
	$(".edit_input").delegate(".isYang","change",function(e){
		setQuantity( $(this),3 );
		$(this).parents('.padding_right_a').find('.goods-quantity').text('X' + $(this).val());
	});

    // 购物车结算
    $('.J_settlement').bind('click',function(e){
        //先检查是否选择了商品
        if($("input[type='checkbox']:checked").length == 0 ){
            alert('您还没有选中商品呢~~');
            return false;
        }
        var form = $('<form>').attr({
            'action':'<{link app=b2c ctl=wap_cart act=checkout}>',
            'method':'post'
        }).append($('.pt-list').clone());
        $('#divCartHide').append(form);
        form.submit();
        // $('<form>').attr({
        //     'action':'<{link app=b2c ctl=wap_cart act=checkout}>',
        //     'method':'post'
        // }).append($('.pt-list').clone()).submit();
        // return false;
    });
	$('.nav_top_bg').eq(0).hide();

      //全选或多选处理  add by guomin 2018.06.04    start
      var CheckAll = $('#items_check_all'),Checks = $('#cart_main').find("input[name^='check']");
      var removeUrl = '<{link app=b2c ctl=wap_cart act=remove}>';
      var cls = Checks.length;
      if (cls >0 ){
          //判断是否全部被选中函数
          function isAllChecked() {
              for(var i = 0; i < cls;i ++) {
                  if(!Checks[i].checked) return false;
              }
              return true;
          }

          //统计购物车中已选择的商品数量
          function toalnum(){
              var num = 0;
              Checks.each(function(index,item){
                  if(item.checked){
                      var itemnum = parseInt($(item).parents('.pt-h-item').find('.goods-quantity').attr('quantity'));
                      num = num + itemnum;
                  }
              })
              return num;
          }

          //给选中的商品item加上状态函数
          function itemChecked (el){
              var item = $(el);
              // item.parents('.pt-h-item').toggleClass('active').css('background',el.checked ? '#efefef':'#fff');
              updateGoodsMark(item);
          }

          //先执行一次判断，如果所有的商品都被选择，全选按钮设置为选中状态
          CheckAll.prop('checked',isAllChecked());

          //执行购物车数量统计函数，更改已选择数量
          $('.J_settlement').find('.checknum').text(toalnum());
          $('.top_cart').find('span').html(toalnum());
          $('#cart_main').bind('tap', function(e){
              var target = e.target;
              if(target.tagName.toLowerCase() == 'label' ){
                  var prev=$(target).prev()[0];
                  if (prev.type=='checkbox' && prev.tagName.toLowerCase()=='input') {
                      if (prev.name=='allcheck'){
                          Checks.each(function(index,item){
                              var checked = item.checked = CheckAll.prop('checked');
                              itemChecked(item);
                          });
                      } else{
                          CheckAll.prop('checked',isAllChecked());
                          itemChecked(target);
                      }
                  }
                  //变更已选择商品数量
                  $('.J_settlement').find('.checknum').text(toalnum());

              }
          })
      }
      //add by guomin 2018.06.04     end

      //add by guomin 2018.06.04 批量删除
      $('.J-remove').on('click',function(e){
          //e.preventDefault();
          if(!confirm('您确认要批量删除所选商品？')) return false;

          //用数组存放参数组
          var data = [];
          Checks.each(function(index,item){
              if(item.checked){
                  var thisParent = $(this).parents('.pt-h-item');
                  data.push($('<form action=""></form>').append(thisParent.clone()).serialize()+'&response_type=true');
                  thisParent.remove();
              }
          });
          if (data.length===0){
              alert('请选择至少一项');
              return false;
          }
          var strdata = data.join(',');
          //一次性提交
          $.post(removeUrl,strdata,function(re){
              var rs = JSON.parse(re);
              if(rs.is_empty) return location.reload();
              $('.bottom_count_prix').find('span').html(rs.sub_total.promotion_subtotal);
              $('.J_settlement').find('span').html(rs.number.cart_number);
              $('.top_cart').find('span').html(rs.number.cart_number);
              if(rs.error) return alert(rs.error);
              // location.reload();
          });
          return false;
      });

      //add by guomin 2018.06.04 批量收藏
      var checkbox = $('input[name^="check"]');
      $('.btn-addfav').bind('click',function(e){
          e.preventDefault();
          checkbox.each(function(index,item){
              var gid =  $(item).parents('.pt-h-item').find('input[name=goods_id]').attr('value');
              var data = 'gid='+gid + '&type=goods';
              var fbtn = $(item).parents('.pt-h-item').find(".favlist");
              if(item.checked){
                  $.post('<{link app=b2c ctl=wap_member act=ajax_fav}>',data,function(re){
                      fbtn.removeClass('btn-addfav').addClass('btn-faved').html('已收藏');
                  });
              }
          });
          if($("input[type='checkbox']:checked").length > 0 ){
              alert('收藏成功')
          }else{
              alert('您还没有选中商品呢~~')
          }
          // return false;
      });
      //  end

      //更新商品价格
      function updateGoodsMark(el){
          var data = $('<form action=""></form>').append(el.parents('.pt-h-item').clone()).serialize();
          $.ajax({
              type:'POST',
              url:'<{link app=b2c ctl=wap_cart act=update}>',
              data: data+"&mark=1&response_type=true",
              //timeout:300,
              async:false,
              success: function(re){
                  var o = JSON.parse(re),

                      promotion = $('#order_promotion .content'),
                      unuse_rule = $('#unused_promotion .content'),
                      ul = '';
                  if(o.promotion){
                      if(o.promotion.order){
                          $.each(o.promotion.order,function(){
                              ul += '<li><b class="f-red">['+this.desc_tag+']</b>'+this.name+'</li>';
                              //if(!check_all_items)window.location.href=window.location.href;
                          });
                          promotion.html(ul);
                          ul = '';
                      }else{
                          promotion.html('');
                      }
                  }else{
                      promotion.html('');
                      //if(!check_all_items)window.location.href=window.location.href;
                  }
                  if(o.unuse_rule){
                      $.each(o.unuse_rule,function(){
                          ul += '<li><b class="f-red">['+this.desc_tag+']</b>'+this.name+'</li>';
                          unuse_rule.html(ul);
                      });
                  }else{
                      unuse_rule.html('');
                  }
                  // el.parents('.pt-h-item').find('d').html(o.edit_ajax_data.buy_price);
                  $('.bottom_count_prix').find('span').html(o.sub_total.promotion_subtotal);
                  $('.J_settlement').find('span').html(o.number.cart_number);
                  $('.top_cart').find('span').html(o.number.cart_number);
              }
          })
      }

});
</script>
